using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Paging;
using SDT.Site.ViewModels;
using SDT.Site.Properties;
using SDT.Lib.Common;
using System.Web.Security;

namespace SDT.Site.Controllers
{
    public class DemandController : Controller
    {
        //
        // GET: /Demand/
        SDTDataContext db = new SDTDataContext();
        public ActionResult Index(int? id, int? catid, int? cityid, int? distrid, int? areaid, int? priceid, int? projectid, int? timeid, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("demand.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("demand.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("demand.orderDir", "orderDir", "desc").ToString();
            int getbyTimeID = Utils.ParseInt(UserState.getUserStateFromRequest("demand.TimeID", "ddlTimeCenter", 0));
            switch (order)
            {
                case "AddDate":
                    orderDir = "desc";
                    break;
                case "nViews":
                    orderDir = "desc";
                    break;
                case "TotalCost":
                    orderDir = "asc";
                    break;
            }
            ViewData["orderDir"] = orderDir;
            ViewData["order"] = order;
            DemandSearchModels p = new DemandSearchModels();
            p.AreaID = areaid;
            p.CategoryID = catid;
            p.CityID = cityid;
            p.DistrictID = distrid;
            p.PriceID = priceid;
            p.TimeID = getbyTimeID >= 0 ? getbyTimeID : timeid.Value;
            p.TypeID = id;
            p.ProjectID = projectid;
            p.Keyword = Request["key"] != null ? Request["key"] : string.Empty;
            p.Demands = DemandManager.GetList(p.TypeID, p.CategoryID, p.CityID, p.DistrictID,
                p.AreaID, p.PriceID, p.ProjectID, p.TimeID, p.Keyword, 0, 1,
                order, orderDir, pageIndex, Utils.ParseInt(Settings.Default.ProductPageSize));
            p.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");

            if (p.CityID > 0)
            {
                p.Districts = DemandManager.GetDistrict(p.TypeID.Value, p.CategoryID.Value, p.CityID.Value);
                p.City = db.Cities.Where(e => e.ID == p.CityID).SingleOrDefault();
            }
            else
            {
                p.Districts = new List<District>();
            }
            p.Categories = id > 0 ? DemandManager.GetObjChildByType(id.Value) : null;
            p.Cities = DemandManager.GetCity(p.TypeID.Value, p.CategoryID.Value);
            p.ConvertPrices = DemandManager.GetConvertPrice(p.TypeID.Value);
            p.ConvertAreas = DemandManager.GetConvertArea(p.TypeID.Value);
            p.DemandTypes = db.DemandTypes.ToList();




            p.DemandType = db.DemandTypes.Where(e => e.ID == p.TypeID).SingleOrDefault();
            p.Category = db.DemandCategories.Where(e => e.ID == p.CategoryID).SingleOrDefault();
            p.District = db.Districts.Where(e => e.ID == p.DistrictID).SingleOrDefault();
            p.ConvertPrice = db.DemandConvertPrices.Where(e => e.ID == p.PriceID).SingleOrDefault();
            p.ConvertArea = db.DemandConvertAreas.Where(e => e.ID == p.AreaID).SingleOrDefault();


            return View(p);
        }
        public ActionResult Details(int id)
        {
            DemandDetailsModels p = new DemandDetailsModels();
            p.Demand = db.Demands.Where(e => e.ID == id).SingleOrDefault();

            p.Directions = Utils.StringToDictionaryIntString(Settings.Default.ProductDirection, ",");

            p.DemandSearch = new DemandSearchModels();
            p.DemandSearch.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            if (p.Demand.CityID > 0)
            {
                p.DemandSearch.Districts = DemandManager.GetDistrict(p.Demand.DemandTypeID.Value, p.Demand.CatID, p.Demand.CityID.Value);
                p.DemandSearch.City = p.Demand.City;
            }
            else
            {
                p.DemandSearch.Districts = new List<District>();
            }
            p.DemandSearch.Categories = DemandManager.GetObjChildByType(p.Demand.DemandTypeID.Value);
            p.DemandSearch.Cities = DemandManager.GetCity(p.Demand.DemandTypeID.Value, p.Demand.CatID);
            p.DemandSearch.ConvertPrices = DemandManager.GetConvertPrice(p.Demand.DemandTypeID.Value);
            p.DemandSearch.ConvertAreas = DemandManager.GetConvertArea(p.Demand.DemandTypeID.Value);
            p.DemandSearch.DemandTypes = db.DemandTypes.ToList();


            p.DemandSearch.DemandType = p.Demand.DemandType;
            p.DemandSearch.Category = p.Demand.DemandCategory;
            p.DemandSearch.District = p.Demand.District;
            p.DemandSearch.ConvertPrice = p.Demand.DemandConvertPrice;
            p.DemandSearch.ConvertArea = p.Demand.DemandConvertArea;

            p.DemandSearch.AreaID = p.Demand.ConvertAreaID;
            p.DemandSearch.CategoryID = p.Demand.CatID;
            p.DemandSearch.CityID = p.Demand.CityID;
            p.DemandSearch.DistrictID = p.Demand.DistrictID;
            p.DemandSearch.PriceID = p.Demand.ConvertPriceID;
            p.DemandSearch.TimeID = 0;
            p.DemandSearch.TypeID = p.Demand.DemandTypeID;
            p.DemandSearch.ProjectID = 0;
            p.DemandSearch.PathTitle = p.Demand.Title;
            p.Keyword = string.Empty;

            return View(p);
        }
        [HttpPost()]
        public ActionResult Search(DemandSearchModels p)
        {

            p.AreaID = Utils.ParseInt(Request["ddlArea"], 0); ;
            p.CategoryID = Utils.ParseInt(Request["ddlCategory"], 0);
            p.CityID = Utils.ParseInt(Request["ddlCity"], 0);
            p.DistrictID = Utils.ParseInt(Request["ddlDistrict"], 0);
            p.PriceID = Utils.ParseInt(Request["ddlPrice"], 0);
            p.TimeID = Utils.ParseInt(Request["ddlTime"], 0);
            p.TypeID = Utils.ParseInt(Request["ddlType"], 0);
            p.ProjectID = 0;
            p.Keyword = Request["txtKeyword"] != null ? Request["txtKeyword"] : string.Empty;

            var path = string.Format("index/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}",
                   p.TypeID.HasValue ? p.TypeID.Value : 0,
                   p.CategoryID.HasValue ? p.CategoryID.Value : 0,
                   p.CityID.HasValue ? p.CityID.Value : 0,
                   p.DistrictID.HasValue ? p.DistrictID.Value : 0,
                   p.AreaID.HasValue ? p.AreaID.Value : 0,
                   p.PriceID.HasValue ? p.PriceID.Value : 0,
                   p.ProjectID.HasValue ? p.ProjectID.Value : 0,
                   p.TimeID.HasValue ? p.TimeID.Value : 0);
            if (p.Keyword != null && p.Keyword != string.Empty) path = path + "?key=" + p.Keyword;
            return RedirectToAction(path, "demand");
        }
        public ActionResult List(int id, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("demandlist.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("demandlist.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("demandlist.orderDir", "orderDir", "desc").ToString();
            DemandSearchModels p = new DemandSearchModels();
            var cp = db.Demands.Where(e => e.ID == id).SingleOrDefault();
            p.AreaID = 0;
            p.CategoryID = cp.CatID;
            p.CityID = 0;
            p.DistrictID = 0;
            p.PriceID = 0;
            p.TimeID = 0;
            p.TypeID = cp.DemandTypeID;
            p.ProjectID = 0;
            p.Keyword = string.Empty;
            p.Demands = DemandManager.GetList(p.TypeID, p.CategoryID, p.CityID, p.DistrictID,
                 p.AreaID, p.PriceID, p.ProjectID, p.TimeID, p.Keyword, 0, 1,
                 order, orderDir, pageIndex, Utils.ParseInt(Settings.Default.ProductPageSize));
            p.PathTitle = cp.DemandType.Name + " của " + cp.ContactName;

            p.Categories = DemandManager.GetObjChildByType(cp.DemandTypeID.Value);
            p.Cities = DemandManager.GetCity(cp.DemandTypeID.Value, cp.CatID);
            p.ConvertPrices = DemandManager.GetConvertPrice(cp.DemandTypeID.Value);
            p.ConvertAreas = DemandManager.GetConvertArea(cp.DemandTypeID.Value);
            p.DemandTypes = db.DemandTypes.ToList();
            p.Districts = new List<District>();
            p.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");

            return View(p);
        }
        [ChildActionOnly]
        public ActionResult Lasted(int typeid, int? catid, int number, string order, string orderDir)
        {
            var p = new DemandListModels();
            var db = new SDTDataContext();
            var l = db.Demands.Where(e => typeid > 0 ? e.DemandTypeID == typeid : true)
                .Where(e => catid > 0 ? e.CatID == catid.Value : true)
                .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            p.Demands = l;
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult OtherItems(int id, int number, string title)
        {
            var a = new DemandListModels();
            var current_product = db.Demands.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Demands.Where(e => e.DemandCategory.ID == current_product.CatID)
                .Where(e => e.PubYN == true)
                .Where(e => e.ID != id)
                .Where(e => e.DistrictID == current_product.DistrictID).OrderByDescending(e => e.ID).Take(number).ToList(); ;
            ViewData["Title"] = title;
            a.Demands = l;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult OtherItemsInCity(int id, int number, string title)
        {
            var p = new DemandListModels();
            var current_product = db.Demands.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Demands.Where(e => e.DemandCategory.ID == current_product.CatID)
                .Where(e => e.PubYN == true)
                .Where(e => e.ID != id)
                .Where(e => e.CityID == current_product.CityID).OrderByDescending(e => e.ID).Take(number).ToList(); ;
            ViewData["Title"] = title;
            p.Demands = l;
            return View(p);
        }
        /// <summary>
        /// Poster: Tin cùng người đăng
        /// </summary>
        /// <param name="id"></param>
        /// <param name="number"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult Poster(int id, string title)
        {
            var a = new DemandListModels();
            var current_product = db.Demands.Where(e => e.ID == id).SingleOrDefault();
            var l = db.Demands.Where(e => e.AddBy == current_product.AddBy)
                .Where(e => e.PubYN == true)
                .OrderByDescending(e => e.ID).ToList(); ;
            ViewData["Title"] = title;
            a.Demands = l;
            a.CurrentDemand = current_product;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult LatestComments(int id, int number)
        {
            var latestC = new List<Comment>();
            try
            {
                latestC = DemandManager.GetComments(id, true, number).ToList();
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
            }
            return PartialView(latestC);
        }
        [ChildActionOnly]
        public ActionResult Comment(int id)
        {
            CommentEditModels c = new CommentEditModels();
            c.ObjectID = id;
            var u = Membership.GetUser();
            if (u != null)
            {
                c.FullName = u.UserName;
                c.Email = u.Email;
            }
            return PartialView(c);
        }
    }
}
